package com.ggy.babybed.socketwork.command;

import com.ggy.babybed.model.SwayModel;
import com.ggy.babybed.socketwork.NetworkConstant;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * @author gonggy
 *
 */
public class SwayCommand extends BaseCommand {
    private String result;
    private SwayModel model;

    public SwayCommand(SwayModel model) {
        this.model = model;
    }

    public String getResult(){
        return result != null ? result : "";
    }

    @Override
    public boolean write(OutputStream outStream) throws IOException {
        if(null != outStream){
            OutputStreamWriter writer = getStringWriter(outStream);
            StringBuffer buffer = new StringBuffer();
            buffer.append(String.format("%d%s", model.getID(), NetworkConstant.SEPARATOR));//ID
            buffer.append(String.format("%s%s", model.getName(), NetworkConstant.SEPARATOR)); //Name
            buffer.append(String.format("%s%s", model.getPassword(), NetworkConstant.SEPARATOR));//password
            buffer.append(String.format("%d%s", model.getRange(), NetworkConstant.SEPARATOR));//fudu
            buffer.append(String.format("%d%s", model.getRate(), NetworkConstant.SEPARATOR));//pinlv
            buffer.append(NetworkConstant.END_FLAG);
            writer.write(buffer.toString());
            writer.flush();
            return true;
        }
        return false;
    }

    @Override
    public boolean read(InputStream inStream) throws IOException {
        String firstLine = readLine(inStream);
        result = firstLine;
        if(firstLine.startsWith(NetworkConstant.SUCCESS_CODE)){
            return true;
        } else if(firstLine.startsWith(NetworkConstant.ERROR_CODE)){
            return false;
        } else {
            throw new IOException("不能识别的返回结果");
        }
    }

}

